package com.netsdk.service.impl;

import cn.hutool.core.util.StrUtil;
import com.netsdk.bean.CardDto;
import com.netsdk.bean.Result;
import com.netsdk.common.Res;
import com.netsdk.demo.module.GateModule;
import com.netsdk.exception.ServiceException;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.service.CardService;
import com.netsdk.utils.CheckUtils;
import com.netsdk.utils.ResultUtil;
import com.sun.jna.Memory;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;

/**
 * 卡操作功能实现
 *
 * @author Yan Xu
 * @version 1.0
 * @date 2021/8/6
 * Copyright © goodits
 */
@Service
public class CardServiceImpl implements CardService {

    @Override
    public List<CardDto> getList(String deviceNo, String cardNo) {
        List<CardDto> cardDtoList = new LinkedList<>();
        // 卡号：  为空，查询所有的卡信息
        // 获取查询句柄
        if (!GateModule.findCard(cardNo)) {
            return cardDtoList;
        }
        try {
            int count = 0;
            int index;
            int nFindCount = 10;

            // 查询具体信息
            while (true) {
                NetSDKLib.NET_RECORDSET_ACCESS_CTL_CARD[] pstRecord = GateModule.findNextCard(nFindCount);
                if (pstRecord == null) {
                    break;
                }

                for (int i = 0; i < pstRecord.length; i++) {
                    index = i + count * nFindCount;

                    try {
                        CardDto cardDto = new CardDto();

                        // 序号
                        cardDto.setSerialNumber(String.valueOf(index + 1));
                        // 卡号
                        cardDto.setCardNo(new String(pstRecord[i].szCardNo).trim());
                        // 卡名
                        cardDto.setCardName(new String(pstRecord[i].szCardName, "GBK").trim());
                        // 用户ID
                        cardDto.setUserId(new String(pstRecord[i].szUserID).trim());
                        // 卡密码
                        cardDto.setCardPasswd(new String(pstRecord[i].szPsw).trim());
                        // 卡状态
                        cardDto.setCardStatus(pstRecord[i].emStatus);
                        cardDto.setCardStatusName(Res.string().getCardStatus(pstRecord[i].emStatus));
                        // 卡类型
                        cardDto.setCardType(pstRecord[i].emType);
                        cardDto.setCardTypeName(Res.string().getCardType(pstRecord[i].emType));
                        // 使用次数
                        cardDto.setUseTimes(String.valueOf(pstRecord[i].nUserTime));
                        // 是否首卡
                        cardDto.setFirstEnter(pstRecord[i].bFirstEnter);
                        // 是否有效
                        cardDto.setEnable(pstRecord[i].bIsValid);
                        // 有效开始时间
                        cardDto.setStartTime(pstRecord[i].stuValidStartTime.toStringTimeEx());
                        // 有效结束时间
                        cardDto.setEndTime(pstRecord[i].stuValidEndTime.toStringTimeEx());

                        cardDto.setRecordNo(pstRecord[i].nRecNo);
                        cardDtoList.add(cardDto);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                if (pstRecord.length < nFindCount) {
                    break;
                } else {
                    count++;
                }

            }
        } finally {
            // 关闭查询接口
            GateModule.findCardClose();
        }
        return cardDtoList;
    }

    @Override
    public Result add(String deviceNo, CardDto cardDto, Memory memory) {
        CheckUtils.checkCardDtoAndMemory(cardDto, memory);
        // 先添加卡，卡添加成功后，再添加图片
        int useTimes;
        if (StrUtil.isBlank(cardDto.getUseTimes())) {
            useTimes = 0;
        } else {
            useTimes = Integer.parseInt(cardDto.getUseTimes());
        }

        boolean bCardFlags = GateModule.insertCard(cardDto.getCardNo(), cardDto.getUserId(), cardDto.getCardName(),
                cardDto.getCardPasswd(), cardDto.getCardStatus(),
                cardDto.getCardType(), useTimes,
                cardDto.getFirstEnter(), cardDto.getEnable(), cardDto.getStartTime(), cardDto.getEndTime());
        String cardError = "";
        if (!bCardFlags) {
            cardError = ToolKits.getErrorCodeShow();
        }

        boolean bFaceFalgs = GateModule.addFaceInfo(cardDto.getUserId(), memory);
        String faceError = "";
        if (!bFaceFalgs) {
            faceError = ToolKits.getErrorCodeShow();
        }
        // 添加卡信息和人脸成功
        if (bCardFlags && bFaceFalgs) {
            return ResultUtil.success(Res.string().getSucceedAddCardAndPerson());
        }
        // 添加卡信息和人脸失败
        if (!bCardFlags && !bFaceFalgs) {
            throw new ServiceException(Res.string().getFailedAddCard() + " : " + cardError);
        }
        // 添加卡信息成功，添加人脸失败
        if (bCardFlags) {
            throw new ServiceException(Res.string().getSucceedAddCardButFailedAddPerson() + " : " + faceError);
        }
        // 卡信息已存在，添加人脸成功
        throw new ServiceException(Res.string().getCardExistedSucceedAddPerson());
    }



    @Override
    public Result update(String deviceNo, CardDto cardDto, Memory memory) {
        CheckUtils.checkCardDtoAndMemory(cardDto, memory);
        // 先修改卡，卡修改成功后，再修改图片
        int useTimes;
        if (StrUtil.isBlank(cardDto.getUseTimes())) {
            useTimes = 0;
        } else {
            useTimes = Integer.parseInt(cardDto.getUseTimes());
        }

        boolean bCardFlags = GateModule.modifyCard(cardDto.getRecordNo(), cardDto.getCardNo(),
                cardDto.getUserId(), cardDto.getCardName(),
                cardDto.getCardPasswd(), cardDto.getCardStatus(),
                cardDto.getCardType(), useTimes,
                cardDto.getFirstEnter(), cardDto.getEnable(), cardDto.getStartTime(), cardDto.getEndTime());
        if (Boolean.FALSE.equals(bCardFlags)) {
            throw new ServiceException(Res.string().getFailedModifyCard() + " : " + ToolKits.getErrorCodeShow());
        }
        boolean bFaceFalgs = GateModule.modifyFaceInfo(cardDto.getUserId(), memory);
        if (Boolean.FALSE.equals(bFaceFalgs)) {
            throw new ServiceException(Res.string().getSucceedModifyCardButFailedModifyPerson() + " : " + ToolKits.getErrorCodeShow());
        }
        return ResultUtil.success(Res.string().getSucceedModifyCardAndPerson());
    }

    @Override
    public Result updateFace(String deviceNo,String userId, Memory memory) {
        boolean bFaceFalgs = GateModule.modifyFaceInfo(userId, memory);
        if (Boolean.FALSE.equals(bFaceFalgs)) {
            throw new ServiceException("修改人脸失败");
        }
        return ResultUtil.success("更新人脸成功");
    }


    @Override
    public Result delete(String deviceNo, String recordNo, String userId) {
        boolean deleteFaceInfo = GateModule.deleteFaceInfo(userId);
        boolean deleteCard = GateModule.deleteCard(Integer.parseInt(recordNo));
        // 删除人脸和卡信息
        if (deleteFaceInfo && deleteCard) {
            return ResultUtil.success(Res.string().getSucceed());
        }
        throw new ServiceException(ToolKits.getErrorCodeShow());
    }
}
